<template>
  <el-dialog
      :title="isEdit ? '修改主机' : '新增主机'"
      :model-value="visible"
      width="800px"
      append-to-body
      @update:model-value="handleDialogClose"
  >
    <div class="host-edit-layout">
      <!-- 水平标签栏 -->
      <div class="horizontal-tabs">
        <el-radio-group v-model="activeTab" size="default" class="tab-group">
          <el-radio-button value="hostInfo" :disabled="!canAccessOtherTabs && activeTab !== 'hostInfo'">主机信息</el-radio-button>
          <el-radio-button value="specConfig" :disabled="!canAccessOtherTabs">规格配置</el-radio-button>
          <el-radio-button value="ssh" :disabled="!canAccessOtherTabs">SSH配置</el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 表单内容区域 -->
      <div class="form-content">
        <component
            :is="activeTabComponent"
            v-model="form[activeTab]"
            :is-edit="isEdit"
            ref="currentFormRef"
        />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSave"
          :loading="loading"
        >
          {{'保存'  }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue';
import HostInfo from '@/views/os/host/HostInfo.vue';
import SpecConfig from '@/views/os/host/SpecConfig.vue';
import Ssh from '@/views/os/host/Ssh.vue';
import { addHost, updateHost, getHostSsh, addHostSsh, updateHostSsh, getHostSpec, addHostSpec, updateHostSpec,getIdentityList, testHostSsh } from "@/api/os/host";
import { fa } from 'element-plus/es/locales.mjs';
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: Boolean,
  isEdit: Boolean,
  initForm: Object,
});
const emit = defineEmits(['update:visible', 'refresh']);
const identityList = ref([]);
const activeTab = ref('hostInfo');
const loading = ref(false);
const currentFormRef = ref();
const form = reactive({
  hostInfo: {},
  specConfig: {},
  ssh: {},
});
const loadIdentityList = async () => {
  const res = await getIdentityList();
  identityList.value = res.data || [];
};
// 当前主机ID
const currentHostId = ref(null);

// 计算是否可以访问其他标签页（新增时需要有ID才能访问）
const canAccessOtherTabs = computed(() => {
  return props.isEdit || currentHostId.value !== null;
});

// 加载其他标签页的数据
const loadTabData = async () => {
  const tab = activeTab.value;
  if (props.isEdit && props.initForm && props.initForm.id) {
    const hostId = props.initForm.id;
    
    try {
      // 根据当前标签加载对应数据
      if (tab === 'ssh') {
        const sshResponse = await getHostSsh(hostId);
        if (sshResponse.data) {
          form.ssh = { ...sshResponse.data };
        }
      } else if (tab === 'specConfig') {
        const specResponse = await getHostSpec(hostId);
        if (specResponse.data) {
          form.specConfig = { ...specResponse.data };
        }
      }
    } catch (error) {
      console.error('加载标签页数据失败', error);
    }
  }
};

// 监听props.visible变化，重置表单状态
watch(() => props.visible, async (val) => {
  if (val) {
    activeTab.value = 'hostInfo';
    currentHostId.value = null; // 重置主机ID
    if (!props.isEdit) {
      // 新增模式清空表单
      form.hostInfo = {};
      form.specConfig = {};
      form.ssh = {};
    } else if (props.initForm) {
      // 编辑模式填充数据
      const clonedData = JSON.parse(JSON.stringify(props.initForm));
      form.hostInfo = clonedData;
      currentHostId.value = clonedData.id; // 设置当前主机ID
      form.specConfig = {};
      form.ssh = {};
    }
  }
}, { immediate: true });

// 监听标签切换，动态加载数据
watch(activeTab, async (newTab) => {
  if (newTab === 'hostInfo') {
    await loadIdentityList();
  }
  else if (newTab !== 'hostInfo' && props.isEdit && props.initForm && props.initForm.id) {
    await loadTabData();
  }
});

// 动态组件映射
const activeTabComponent = computed(() => {
  const components = {
    hostInfo: HostInfo,
    specConfig: SpecConfig,
    ssh: Ssh,
  };
  return components[activeTab.value] || HostInfo;
});

// 处理弹窗关闭
const handleDialogClose = (value) => {
  if (!value) {
    // 重置表单数据和验证状态
    form.hostInfo = {};
    form.specConfig = {};
    form.ssh = {};
    currentHostId.value = null;
    activeTab.value = 'hostInfo';
    nextTick(() => {
      if (currentFormRef.value && currentFormRef.value.clearValidate) {
        currentFormRef.value.clearValidate();
      }
    });
  }
  emit('update:visible', value);
};

// 取消按钮
const handleCancel = () => {
  // 重置表单数据和验证状态
  form.hostInfo = {};
  form.specConfig = {};
  form.ssh = {};
  currentHostId.value = null;
  activeTab.value = 'hostInfo';
  nextTick(() => {
    if (currentFormRef.value && currentFormRef.value.clearValidate) {
      currentFormRef.value.clearValidate();
    }
  });
  emit('update:visible', false);
};

// 验证当前表单
const validateCurrentForm = async () => {
  if (currentFormRef.value && currentFormRef.value.validate) {
    return await currentFormRef.value.validate();
  }
  return true;
};

// 保存主机基本信息
const saveHostInfo = async () => {
  let response;
  if (form.hostInfo != null && form.hostInfo.id != null) {
    response = await updateHost({ ...form.hostInfo, id: currentHostId.value });
  } else {
    response = await addHost(form.hostInfo);
    if(response.data && response.data.id) {
      currentHostId.value = response.data.id;
    } 
  }
  return response;
};

// 保存SSH配置
const saveSshConfig = async (hostId) => {
  const sshData = { ...form.ssh, hostId };
  // 移除不必要的字段
  delete sshData.useOriginalPwd;
  // 根据认证方式移除不必要的字段
  if (sshData.authType === 'password') {
    delete sshData.identityId;
  } else if (sshData.authType === 'cert') {
    delete sshData.password;
  }
  if (form.ssh != null && form.ssh.id != null) {
    return await updateHostSsh(sshData);
  } else {
    return await addHostSsh(sshData);
  }
};

// 保存规格配置
const saveSpecConfig = async (hostId) => {
  const specData = { ...form.specConfig, hostId };
  
  // 确保日期格式正确
  if (specData.createTime && typeof specData.createTime === 'string') {
    // 如果已经是正确格式，不做处理
    if (!specData.createTime.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
      // 格式化日期
      const date = new Date(specData.createTime);
      if (!isNaN(date.getTime())) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        specData.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
    }
  }
  
  if (specData.exireTime && typeof specData.exireTime === 'string') {
    if (!specData.exireTime.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
      const date = new Date(specData.exireTime);
      if (!isNaN(date.getTime())) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        specData.exireTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
    }
  }

  if (form.specConfig != null && form.specConfig.id != null) {
    return await updateHostSpec(specData);
  } else {
    return await addHostSpec(specData);
  }
};

// 保存逻辑 - 根据当前标签页执行对应的保存方法
const handleSave = async () => {
  try {
    // 验证当前表单
    await validateCurrentForm();

    loading.value = true;
    
    let hostId = currentHostId.value;
    let response;
    // 根据当前标签页执行对应的保存方法
    switch (activeTab.value) {
      case 'hostInfo':
        response = await saveHostInfo();
        if (response.data && response.data.id) {
          hostId = response.data.id;
          currentHostId.value = hostId;
          // 如果是新增，更新表单中的ID
          if (!props.isEdit) {
            form.hostInfo.id = hostId;
            form.specConfig.hostId = hostId;
            form.ssh.hostId = hostId;
          }
        }
        break;
        
      case 'ssh':
        if (!hostId) {
          throw new Error('请先保存主机基本信息');
        }
        response = await saveSshConfig(hostId);
        break;
        
      case 'specConfig':
        if (!hostId) {
          throw new Error('请先保存主机基本信息');
        }
        response = await saveSpecConfig(hostId);
         if (response.data && response.data.id) {
          // 如果是新增，更新表单中的ID
          if (!props.isEdit) {
            form.specConfig.id = response.data.id;
          }
        }
        break;
    }

    if (response && response.code === 200) {
      proxy.$modal.msgSuccess(props.isEdit ? "修改成功" : "保存成功");
        if (activeTab.value === 'ssh'){
          emit('refresh', false);
          emit('update:visible', false);
        }
    }
  } catch (error) {
    console.error('保存失败', error);
    if (error && error.errorFields) {
      proxy.$modal.msgError("请完善必填信息");
    } else if (error.message) {
      proxy.$modal.msgError(error.message);
    } else {
      proxy.$modal.msgError("操作失败");
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.host-edit-layout {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.horizontal-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.tab-group {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
}

.tab-group .el-radio-button {
  margin: 0 2px;
}

.tab-group .el-radio-button:first-child .el-radio-button__inner {
  border-radius: 4px 0 0 4px;
}

.tab-group .el-radio-button:last-child .el-radio-button__inner {
  border-radius: 0 4px 4px 0;
}

.tab-group .el-radio-button__inner {
  padding: 8px 16px;
  white-space: nowrap;
}

.form-content {
  min-height: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 禁用状态的样式 */
.tab-group .el-radio-button.is-disabled .el-radio-button__inner {
  color: #a8abb2;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  cursor: not-allowed;
}
</style>